package com.atguigui.leetcode1;

/**
 * 1572. 矩阵对角线元素的和
 * Project: leetcode
 * Package: com.atguigui.leetcode1
 * Version: 1.0
 * <p>
 * Created by WJX on 2023/8/11 8:43
 */
public class P1572MatrixDiagonalSum {
    public static void main(String[] args) {
        Solution solution = new P1572MatrixDiagonalSum().new Solution();
        int[][] mat = new int[4][4];
        int[] row1 = {7, 3, 1, 9};
        int[] row2 = {3, 4, 6, 9};
        int[] row3 = {6, 9, 6, 6};
        int[] row4 = {9, 5, 8, 5};

        mat[0] = row1;
        mat[1] = row2;
        mat[2] = row3;
        mat[3] = row4;
        solution.diagonalSum(mat);
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public int diagonalSum(int[][] mat) {
            int n = mat.length;

            if (n == 1) return mat[0][0];


            int x = 0, y = 0;
            for (int i = 0; i < n; i++) {
                x += mat[i][i];
            }
            for (int i = n - 1; i >= 0; i--) {
                y += mat[n - 1 - i][i];
            }


            if (n % 2 != 0) {
                x -= mat[n / 2][n / 2];
            }


            return x + y;
        }
    }
}
